#include "Cell.h"


Cell::Cell(const Ogre::String &name,
				  OgreBulletDynamics::DynamicsWorld *world,
				  kdtree* kdFood,
				  const short collisionGroup,
				  const short collisionMask) :
				  BioEntity (name,world,collisionGroup,collisionMask)
{
	idle = new Idle(this);
	searchFood = new SearchFood(this);
	goEatFood = new GoEatFood(this);


	action = searchFood;
	this->kdFood = kdFood;
}

Cell::~Cell()
{
    //dtor
}

void Cell::stepBioSimulation(Real elapsedTime) {
	BioEntity::stepBioSimulation(elapsedTime);

	if (lifeState == ALIVE) {
		action = action->stepBioSimulation(elapsedTime);
	}

}

Cell::CellAction* Cell::Idle::stepBioSimulation(Real elapsedTime)
{
	if (cell->energy < 95) { // TODO Parameterize "hungry energy level"
		return cell->searchFood;
	}
	return cell->idle;
}

Cell::CellAction* Cell::GoEatFood::stepBioSimulation(Real elapsedTime)
{
	Ogre::Vector3 foodDir = foodPos - cell->getWorldPosition();
	Ogre::Vector3 vel = cell->getLinearVelocity();
	Ogre::Vector3 f = foodDir + (foodDir - vel);
	cell->applyForce(f, Ogre::Vector3(0,0,0));
//	cell->setLinearVelocity(f);
	return cell->goEatFood;
}



Cell::CellAction* Cell::SearchFood::stepBioSimulation(Real elapsedTime)
{
	struct kdres* res;
	double pos[3];
	Ogre::Vector3 cellPos = cell->getWorldPosition();
//	res = kd_nearest3(cell->kdFood, cellPos.x, cellPos.y, cellPos.z);
	res = kd_nearest3(cell->kdFood, pos[0], pos[1], pos[2]);

	BioEntity* food = (BioEntity*)kd_res_item(res,pos);
	cell->goEatFood->foodPos = food->getWorldPosition();
//	cell->goEatFood->foodPos.x = pos[0];
//	cell->goEatFood->foodPos.y = pos[1];
//	cell->goEatFood->foodPos.z = pos[3];
	return cell->goEatFood;
}

void Cell::collideWith(BioEntity* other) {
	energy += other->energy;
	getBu
}
